# Clean Environment -------------------------------------------------------
rm(list = ls())

# Load Data ---------------------------------------------------------------

task_dataset <- readRDS("hungary_choices.rds")
hungary_df <- readRDS("hungary_survey.rds")
hungary_df <- hungary_df[-1, ]
source("figure_design.R")

# Measurement model -------------------------------------------------------

cfaord <- '
  lib =~ Q101_1 + Q101_2 + Q101_3
  maj =~ Q101_10 + Q101_11 + Q101_12
  auth =~ Q101_4 + Q101_5 + Q101_6

  lib ~~ maj
  lib ~~ auth
  auth ~~ maj
'

fit_ord <- cfa(cfaord, ordered = TRUE, data = hungary_df)
summary(fit_ord, fit.measures = TRUE)
fitmeasures(fit_ord, c('cfi', 'rmsea', 'rmsea.ci.upper', 'bic'))

factor_scores <- data.frame(lavPredict(fit_ord))

hungary_uod <- cbind(hungary_df, factor_scores) %>%
  dplyr::select(RecordNo, lib, maj, auth, Q104, Q124, Q128, birthyear, gender) %>%
  mutate(
    party_preference = case_when(
      Q104 == 1 ~ 'Fidesz',
      Q104 == 2 ~ 'Christian Democratic People\'s Party',
      Q104 == 3 ~ 'Jobbik',
      Q104 == 4 ~ 'Hungarian Socialist Party',
      Q104 == 5 ~ 'Democratic Coalition',
      Q104 == 6 ~ 'Dialogue for Hungary',
      Q104 == 7 ~ 'Momentum',
      Q104 == 8 ~ 'Hungary\'s Green Party',
      Q104 %in% c(9, 10) ~ 'Don\'t know/none'
    ),
    party_preference = factor(party_preference, levels = c(
      'Fidesz', 'Christian Democratic People\'s Party', 'Jobbik',
      'Hungarian Socialist Party', 'Democratic Coalition', 
      'Dialogue for Hungary', 'Momentum', 'Hungary\'s Green Party', 
      'Don\'t know/none'
    )),
    income = case_when(
      Q128 == 1 ~ 'Below 125,000 HUF',
      Q128 == 2 ~ 'Between 125,000 and 300,000 HUF',
      Q128 == 3 ~ 'Between 300,000 and 500,000 HUF',
      Q128 == 4 ~ 'Between 500,000 and 750,000 HUF',
      Q128 == 5 ~ 'Between 750,000 and 1,500,000 HUF',
      Q128 == 6 ~ 'Above 1,500,000 HUF',
      TRUE ~ 'No response'
    ),
    income = factor(income, levels = c(
      'Below 125,000 HUF', 'Between 125,000 and 300,000 HUF', 
      'Between 300,000 and 500,000 HUF', 'Between 500,000 and 750,000 HUF', 
      'Between 750,000 and 1,500,000 HUF', 'Above 1,500,000 HUF', 'No response'
    )),
    education = case_when(
      Q124 == 1 ~ 'Primary school (8 primary)',
      Q124 == 2 ~ 'Vocational training',
      Q124 == 3 ~ 'High school, graduation',
      Q124 == 4 ~ 'College, university',
      TRUE ~ 'No response'
    ),
    education = factor(education, levels = c(
      'Primary school (8 primary)', 'Vocational training', 
      'High school, graduation', 'College, university', 'No response'
    )),
    age = 2022 - as.numeric(birthyear),
    gender = case_when(
      gender == 1 ~ 'Male',
      gender == 2 ~ 'Female'
    ),
    gender = factor(gender, levels = c('Male', 'Female'))
  ) %>%
  dplyr::select(-Q104, -Q128, -Q124)

# Data Transformation -----------------------------------------------------

task_dataset_subset <- task_dataset %>%
  dplyr::select(RecordNo, cand, set, violation, democracy, decision_numeric) %>%
  pivot_wider(names_from = cand, values_from = c(violation, democracy, decision_numeric)) %>%
  left_join(hungary_uod, by = "RecordNo", relationship = "many-to-many") %>%
  mutate(vote_lib = case_when(
    ((democracy_1 != "lib: equal rights for all" | violation_1 != "judges should ensure constitutionality") &
       democracy_2 == "lib: equal rights for all" & violation_2 == "judges should ensure constitutionality" & 
       decision_numeric_2 == 1) |
      ((democracy_2 != "lib: equal rights for all" | violation_2 != "judges should ensure constitutionality") &
         democracy_1 == "lib: equal rights for all" & violation_1 == "judges should ensure constitutionality" & 
         decision_numeric_1 == 1) ~ 1,
    ((democracy_1 != "lib: equal rights for all" | violation_1 != "judges should ensure constitutionality") &
       democracy_2 == "lib: equal rights for all" & violation_2 == "judges should ensure constitutionality" & 
       decision_numeric_1 == 1) |
      ((democracy_2 != "lib: equal rights for all" | violation_2 != "judges should ensure constitutionality") &
         democracy_1 == "lib: equal rights for all" & violation_1 == "judges should ensure constitutionality" & 
         decision_numeric_2 == 1) ~ 0
  )) %>%
  filter(!is.na(vote_lib)) %>%
  mutate(RecordNo = droplevels(as.factor(RecordNo)))

# Table F.3 ---------------------------------------------------------------

m1 <- lm_robust(vote_lib ~ lib + party_preference + income + education + income + gender + age, cluster = RecordNo, data = task_dataset_subset) 
m2 <- lm_robust(vote_lib ~ maj + party_preference + income + education + income + gender + age, cluster = RecordNo, data = task_dataset_subset) 
m3 <- lm_robust(vote_lib ~ auth + party_preference + income + education + income + gender + age, cluster = RecordNo, data = task_dataset_subset) 

texreg(list(m1, m2, m3),
       file = "tab_f3.tex",
       custom.header = list("Vote for liberal candidate" = 1:3),
       custom.model.names = c("Liberal","Majoritarian","Authoritarian"),
       include.ci = FALSE,
       digits = 3,
       booktabs = TRUE,
       include.rmse = FALSE,
       custom.coef.map = list(
         "lib" = "Liberal understanding",
         "maj" = "Majoritarian understanding",
         "auth" = "Authoritarian understanding",
         "party_preferenceChristian Democratic People's Party" = "Christian Democratic People's Party",
         "party_preferenceJobbik" = "Jobbik",
         "party_preferenceHungarian Socialist Party" = "Hungarian Socialist Party",
         "party_preferenceDemocratic Coalition" = "Democratic Coalition",
         "party_preferenceDialogue for Hungary" = "Dialogue for Hungary",
         "party_preferenceMomentum" = "Momentum",
         "party_preferenceHungary's Green Party" = "Hungary's Green Party",
         "party_preferenceDon't know/none" = "Don't know/none",
         "incomeBetween 125,000 and 300,000 HUF" = "Between 125,000 and 300,000 HUF",
         "incomeBetween 300,000 and 500,000 HUF" = "Between 300,000 and 500,000 HUF",
         "incomeBetween 500,000 and 750,000 HUF" = "Between 500,000 and 750,000 HUF",
         "incomeBetween 750,000 and 1,500,000 HUF" = "Between 750,000 and 1,500,000 HUF",
         "incomeAbove 1,500,000 HUF" = "Above 1,500,000 HUF",
         "incomeNo response" = "No response ",
         "educationVocational training" = "Vocational training",
         "educationHigh school, graduation" = "High school, graduation",
         "educationCollege, university" = "College, university",
         "educationNo response" = "No response",
         "genderFemale" = "Female (vs. male)",
         "age"="Age"
       ),
       custom.gof.names = c(NA, NA, "$N$ Choices", "$N$ Respondents"),
       groups = list("Party preference (baseline = Fidesz)" = 4:11,
                     "Income (baseline = Below 125,000 HUF)" = 12:17,
                     "Education (baseline = Primary)" = 18:21)
)

# Figure F.1 --------------------------------------------------------------

ggplot(task_dataset_subset, aes(x = lib, y = vote_lib*100)) +
  geom_point(color = "white") +
  geom_hline(yintercept = 50, linetype = "dashed", color = "grey") + # Horizontal line at y = 50
  geom_smooth(method = "gam", formula = y ~ s(x), color = "#1f77b4") + # GAM line
  labs(y = "Votes cast for liberal candidate (%)",
       x = "Liberal understanding") +
  scale_y_continuous(breaks = c(30, 50, 70, 90)) +
  coord_cartesian(ylim = c(28, 90))   ->
  fig_f1a

fig_f1a_hist <- ggMarginal(fig_f1a, type = "histogram",
                                margins = "x")

fig_f1a_hist
dev.copy(pdf, "fig_f1a.pdf",
         width =  3, height = 4)
dev.off()

ggplot(task_dataset_subset, aes(x = maj, y = vote_lib*100)) +
  geom_point(color = "white") +
  geom_hline(yintercept = 50, linetype = "dashed", color = "grey") + # Horizontal line at y = 50
  geom_smooth(method = "gam", formula = y ~ s(x), color = "#1f77b4") + # GAM line
  labs(y = "Votes cast for liberal candidate (%)",
       x = "Majoritarian understanding") +
  scale_y_continuous(breaks = c(30, 50, 70, 90)) +
  coord_cartesian(ylim = c(28, 90))   ->
  fig_f1b

fig_f1b_hist <- ggMarginal(fig_f1b, type = "histogram",
                           margins = "x")

fig_f1b_hist
dev.copy(pdf, "fig_f1b.pdf",
         width =  3, height = 4)
dev.off()

ggplot(task_dataset_subset, aes(x = auth, y = vote_lib*100)) +
  geom_point(color = "white") +
  geom_hline(yintercept = 50, linetype = "dashed", color = "grey") + # Horizontal line at y = 50
  geom_smooth(method = "gam", formula = y ~ s(x), color = "#1f77b4") + # GAM line
  labs(y = "Votes cast for liberal candidate (%)",
       x = "Authoritarian understanding") +
  scale_y_continuous(breaks = c(30, 50, 70, 90)) +
  coord_cartesian(ylim = c(28, 90))   ->
  fig_f1c

fig_f1c_hist <- ggMarginal(fig_f1c, type = "histogram",
                           margins = "x")

fig_f1c_hist
dev.copy(pdf, "fig_f1c.pdf",
         width =  3, height = 4)
dev.off()